/*
 */
package servlet.ajax;

import dao.GenericDAO;
import dao.impl.GenericDAOImpl;
import entity.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Обрабатывает ajax-запросы генерируется js-приложением главной страницы
 * телефонной книги
 *
 * @author Konstantin Chumachenko <kostyachum@gmail.com>
 */
public class PhoneListServlet extends HttpServlet {

    @Override
    protected void doPost(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        JSONObject json = new JSONObject();
        try {
            GenericDAO<OrgUnitType, Long> daoOrgUnitType = new GenericDAOImpl<OrgUnitType, Long>(OrgUnitType.class);
            GenericDAO<Person, Long> daoPerson = new GenericDAOImpl<Person, Long>(Person.class);
            GenericDAO<Phone, Long> daoPhone = new GenericDAOImpl<Phone, Long>(Phone.class);
            GenericDAO<OrgUnitPost, Long> daoOrgUnitPost = new GenericDAOImpl<OrgUnitPost, Long>(OrgUnitPost.class);
            JSONArray jsonArray = new JSONArray();
            String query = request.getParameter("ajax");
            String filter = request.getParameter("filter");
            String searchText = request.getParameter("search_text");
            int searchType = -1;
            try {
                searchType = Integer.parseInt(request.getParameter("search_type"));
            } catch (Exception ex) {
            }
            /**
             * Данные для построения меню
             */
            if (query != null && query.equals("getUnitList")) {
                for (OrgUnitType unitType : daoOrgUnitType.getAll()) {
                    JSONObject unit = new JSONObject();
                    JSONArray content = new JSONArray();
                    for (OrgUnit orgUnit : unitType.getOrgUnitList()) {
                        content.add(orgUnit.getName());
                    }
                    unit.put("name", unitType.getName());
                    unit.put("content", content);
                    jsonArray.add(unit);
                }
                json.put("unitList", jsonArray);
            }

            /**
             * Данные для построения главной таблицы
             */
            if (query != null && query.equals("getPhoneList")) {
                Collection<OrgUnitPost> personList = null;
                if (searchType != -1) {
                    if (searchType == 0) {
                        personList = daoOrgUnitPost.searchByName(searchText);
                    }
                    if (searchType == 1) {
                        personList = daoOrgUnitPost.searchByPhone(searchText);
                    }
                    if (searchType == 2) {
                        personList = daoOrgUnitPost.searchByRoom(searchText);
                    }
                } else {
                    personList = daoOrgUnitPost.getAll();
                }
                /*
                 * Выборка данных из таблицы и заполнения массива
                 */
                for (OrgUnitPost person : personList) {
                    if (filter == null || person.getOrgUnit().getName().equals(filter)) {
                        List row = new ArrayList();
                        Person p = person.getPerson();
                        String phoneLine = "";
                        Set<Phone> phoneList = person.getPhones();
                        for (Phone phone : phoneList) {
                            phoneLine += phone.getType().getName()
                                    + ": " + phone.getNumber()
                                    + "<br>";
                        }

                        row.add(person.getPost().getName());
                        row.add(p.getSurname() + " "
                                + p.getName() + " "
                                + p.getFathername());
                        row.add(phoneLine);
                        row.add(person.getRoom().getName());
                        row.add(person.getOrgUnit().getName());
                        jsonArray.add(row);
                    }
                }
                /*
                 * Формирование ответа
                 */
                String sEcho = request.getParameter("sEcho");
                String iLength = request.getParameter("iDisplayLength");
                int length = 1;
                try {
                    length = Integer.parseInt(iLength);
                } catch (Exception ex) {
                    length = 10;
                }

                json.put("aaData", jsonArray);
                json.put("sEcho", sEcho);
                json.put("iTotalRecords", length);
                json.put("iTotalDisplayRecords", length);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        /*
         * Отправка ответа
         */
        System.out.println(json);
        PrintWriter pw = response.getWriter();
        response.setContentType("text/plain");
        pw.println("" + json.toString() + "");
        pw.flush();

        pw.close();
    }
}
